package com.beyond.core.sched;

import com.beyond.core.codec.SettingRadarProtocol;
import com.beyond.core.common.MD5Util;
import com.beyond.core.handler.ProofTimeHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * 雷达定时对时
 * 描述：
 * @author shulei
 * @date 2021年7月16日
 *
 */
@Component
@Slf4j
public class ProofTime {

    @Value("${schedSendIP}")
    private String schedSendIP;

    @Value("${schedSendPort}")
    private Integer schedSendPort;

    private byte opType = (byte) 0x81;//操作类型
    private byte objectFlag = 0x02;//对象标识

    @Scheduled(cron = "${schedulerTime}")
    @PostConstruct//启动项目先执行一次
    public void pushData() throws IOException {
        //将当前时间转换为数据
        String dateStr = Long.toHexString(System.currentTimeMillis() / 1000);
        byte[] dataByte = MD5Util.hexToByte(dateStr);
        //封装数据包
        byte[] dateByte = SettingRadarProtocol.sendCommand(opType, objectFlag, dataByte);
        //发送时间校准数据包
        EventLoopGroup sendDate = new NioEventLoopGroup();
        try{
            Bootstrap bootstrap= new Bootstrap();
            bootstrap.group(sendDate)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ProofTimeHandler());
            Channel ch = bootstrap.bind(0).sync().channel();
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(dateByte),
                    new InetSocketAddress(schedSendIP, schedSendPort))).sync();
        }catch (Exception e){
            log.error("定时任务启动异常，异常信息：{}", e);
            e.printStackTrace();
        }finally {
            sendDate.shutdownGracefully();
        }
    }
}
